﻿namespace ChessToys.ChessController.Cli
{
    using System;
    using System.Diagnostics;

    public class ChessControllerCli
    {
        private static Stopwatch _stopwatch = new Stopwatch();

        public static void Main(string[] args)
        {
            // parse arguments
            Arguments arguments = Arguments.Parse(args);
            // parse error or info options -> exit
            if (arguments == null)
            {
                return;
            }
            // print white player
            Console.WriteLine(String.Format("white player: {0}", arguments.WhiteController.Name));
            Console.WriteLine(String.Format("black player: {0}", arguments.BlackController.Name));
            // initializa board
            Board board = Board.Default();
            // play
            while (true)
            {
                // color to move
                Color colorToMove = board.ColorToMove;
                Console.WriteLine();
                Console.WriteLine(String.Format("{0} to move:", colorToMove));
                // print board
                board.ToConsole();
                // prepare move
                Move move = null;
                while (move == null)
                {
                    // restart stopwatch
                    _stopwatch.Restart();
                    // invoke controller
                    switch (colorToMove)
                    {
                        case Color.White:
                            move = arguments.WhiteController.NextMove(board);
                            break;
                        case Color.Black:
                            move = arguments.BlackController.NextMove(board);
                            break;
                    }
                    // measure compution time
                    _stopwatch.Stop();
                    // check if move is valid
                    if (!MoveGeneratorUtils.PossibleMoves(board, colorToMove).Contains(move))
                    {
                        move = null;
                    }
                }
                try
                {
                    // show move
                    Console.WriteLine();
                    Console.WriteLine(String.Format("Duration: {0:T}", _stopwatch.Elapsed));
                    Console.WriteLine(String.Format("{0} moves {1}", colorToMove, move.ToString(board)));
                    // apply move
                    board.ApplyMove(move);
                }
                catch (CheckMateException e)
                {
                    Console.WriteLine();
                    Console.WriteLine(String.Format("Check mate - {0} looses the match.", e.LoosingColor));
                    return;
                }
            }
        }
    }
}
